#include "com_form_jbgl.h"
#include "ui_com_form_jbgl.h"

#include "pub_var.h"
#include <QSettings>
#include <QMessageBox>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QSqlError>
#include <QDir>

Form_com_jbgl::Form_com_jbgl(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_com_jbgl)
{
    ui->setupUi(this);

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/com_jbgl").toRect();
    this->setGeometry(rct);
    //ui->ckb_combine->setVisible(false);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);
    md_drug_list = new QSqlQueryModel();
    md_drug_new_price = new QSqlQueryModel();
    md_undrug_list = new QSqlQueryModel();
    md_undrug_new_price = new QSqlQueryModel();
    md_bill_list = new QSqlQueryModel();
    md_bill_content = new QSqlQueryModel();

    dlgDelay = new Pub_pop_delay();

    sq = "create temporary table if not exists tmp_price_detail "
         "("
         "adjust_number int,"   //调价单序号
            "serial_code int," //调价单内序号
            "item_code VARCHAR(12) not null unique, "//药品编码
            "item_name VARCHAR(100) ,"  //trade_name
            "drug_dept_code  VARCHAR(12), " //库房编码
            "drug_type VARCHAR(1),"    //药品类别
            "drug_quality VARCHAR(2),"     //药品性质
            "specs VARCHAR(32),"  //规格
            "producer_code VARCHAR(32),"  //生产厂家
            "pack_unit VARCHAR(32),"//包装单位
            "pack_qty int, "//包装数量
            "min_unit VARCHAR(32),"//最小单位
            "store_sum DECIMAL(12,4),"        //调价库存量
            "pre_wholesale_price DECIMAL(12,4),"  //调价前购入价格
            "pre_retail_price DECIMAL(12,4),"     //调价前零售价格
            "wholesale_price DECIMAL(12,4),"  //调价后购入价格
            "retail_price DECIMAL(12,4),"     //调价后零售价格
            "current_state char(1),"//调价单状态：0、未调价；1、已调价；2、无效"
            "profit_flag char(1), "//盈亏标记1-盈，0-亏
            "dd_adjust_mark char(1), "//药库调价标志
            "ds_adjust_mark char(1), "//药房调价标志
            "inure_time datetime,"  //调价执行时间
            "oper_code varchar(10),"    //
            "oper_name varchar(20),"   //
            "oper_date datetime,"  //
            "mark varchar(100)"    //
            ") ";

    qDebug()<<"临时调价表："<<sq;
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"note","未能成功建立临时价表！");
        return;
    }

    ui->tabWidget->setCurrentIndex(0);

    serial_code = 0;    //调价临时表内部排序号

    sq = "select dept_name, dept_code from com_department "
         "where valid_state = '1' order by dept_name";
    qDebug()<<"提取门诊科室："<<sq;
    oper_dept = pub::fillCombo(ui->cbb_dept_code_2, sq, -1, qrot);
    ui->cbb_dept_code_2->addItem("全部");
    oper_dept.append("^全部^");

    //last_sql;//for data export

}

Form_com_jbgl::~Form_com_jbgl()
{
    delete ui;
}

void Form_com_jbgl::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/com_jbgl", QVariant(this->geometry()));

    emit destroyW( "com_jbgl" );

}

void Form_com_jbgl::on_pb_search_drug_clicked()
{

    QString key = ui->le_key_drug->text().trimmed();
    sq = " select pha.TRADE_NAME 药品名称, pha.SPECS 规格, f_c.fac_name 厂家, pha.drug_code ," // 0 - 3
            " pha.approve_info, pha.retail_price, pha.purchase_price,"  // 4 - 6
            " pha.pack_unit, pha.pack_qty, sum(sto.store_sum), "  // 7 - 9
            " pha.drug_type, pha.drug_quality, pha.producer_code, pha.min_unit, pha.fee_code "  // 10 - 14
            " from pha_com_baseinfo pha "
            " LEFT JOIN PHA_COM_COMPANY f_c ON f_c.FAC_CODE = pha.PRODUCER_CODE "
            " LEFT JOIN pha_com_stockinfo sto ON sto.drug_code = pha.drug_code "
            " where (pha.SPELL_CODE like '%%1%' or TRADE_NAME like '%%2%') "
            " %3 %4 "
            " group by TRADE_NAME,specs, f_c.fac_name, pha.drug_code, pha.approve_info, "
            " pha.retail_price, pha.purchase_price, pha.pack_unit, pha.pack_qty, "
            " pha.drug_type, pha.drug_quality, pha.producer_code, pha.min_unit, pha.fee_code"
            " order by TRADE_NAME";

    sq = sq.arg(key.toUpper()).arg(key);

    QString check_store_sum = "";
    if(ui->ckb_none_0->isChecked())
    {
        check_store_sum = " and sto.store_sum > 0 ";
    }
    sq = sq.arg(check_store_sum);

    QString check_valid = "";
    if(ui->ckb_inuse_drug->isChecked())
    {
        check_valid = " and pha.valid_state = '1' ";
    }
    sq = sq.arg(check_valid);

    qDebug()<<"药品调价，目录检索："<<sq;
    md_drug_list->setQuery(sq, pub::db_o);

    ui->tv_drug_source->setModel(md_drug_list);
    int width = ui->tv_drug_source->width();
    pub::setColumnWidth(ui->tv_drug_source, "0.3^0.2^0.4^0^0^0^0^0^0^0^0^0", width);

}

void Form_com_jbgl::on_tv_drug_source_clicked(const QModelIndex &index)
{

    item_info.clear();
    item_info["trade_name"] = index.siblingAtColumn(0).data().toString();
    item_info["specs"] = index.siblingAtColumn(1).data().toString();
    item_info["fac_name"] = index.siblingAtColumn(2).data().toString();
    item_info["drug_code"] = index.siblingAtColumn(3).data().toString();
    item_info["approve_info"] = index.siblingAtColumn(4).data().toString();

    item_info["retail_price"] = index.siblingAtColumn(5).data().toString();
    item_info["purchase_price"] = index.siblingAtColumn(6).data().toString();
    item_info["pack_unit"] = index.siblingAtColumn(7).data().toString();
    item_info["pack_qty"] = index.siblingAtColumn(8).data().toString();
    item_info["store_sum"] = index.siblingAtColumn(9).data().toString();

    item_info["drug_type"] = index.siblingAtColumn(10).data().toString();
    item_info["drug_quality"] = index.siblingAtColumn(11).data().toString();
    item_info["producer_code"] = index.siblingAtColumn(12).data().toString();
    item_info["min_unit"] = index.siblingAtColumn(13).data().toString();
    item_info["fee_code"] = index.siblingAtColumn(14).data().toString();

    ui->le_prov_info->setText(index.siblingAtColumn(4).data().toString());
    ui->le_factory->setText(index.siblingAtColumn(2).data().toString());
    ui->le_pack_qty->setText(index.siblingAtColumn(8).data().toString());
    ui->le_pack_unit->setText(index.siblingAtColumn(7).data().toString());
    ui->le_store_sum->setText(index.siblingAtColumn(9).data().toString());
    ui->le_purchase_price->setText(QString::number(index.siblingAtColumn(6).data().toDouble(),'f',2));
    ui->le_retail_price->setText(QString::number(index.siblingAtColumn(5).data().toDouble(),'f',2));

    ui->le_price_after->clear();
    ui->le_memo->clear();
}

void Form_com_jbgl::on_tv_drug_source_doubleClicked(const QModelIndex &index)
{
    on_tv_drug_source_clicked(index);
}

bool Form_com_jbgl::check_status_u()
{
    if(ui->le_item_code_u->text().isEmpty())
    {
        QMessageBox::information(this, "注意", "未选定有效项目！");
        return false;
    }

    if(ui->le_price_after_u->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "项目价格不可以为空白！");
        ui->le_price_after->setFocus();
        return false;
    }

    double testDouble = ui->le_price_after_u->text().trimmed().toDouble();
    if( qFuzzyCompare(testDouble, 0))
    {
        QMessageBox::warning(this, "注意", "项目价格为0，请注意核实！");
//        return false;
    }

    if( testDouble + 0.0001 < 0)
    {
        QMessageBox::warning(this, "注意", "项目价格不可以为负！");
        return false;
    }

    if( qFuzzyCompare(testDouble, ui->le_retail_price_u->text().toDouble()))
    {
        QMessageBox::warning(this, "注意", "项目价格无变化！");
        return false;
    }

    return true;
}

bool Form_com_jbgl::check_status()
{

    if(item_info["fee_code"] != "003")
    {
        //非草药，检查批准文号
        if(ui->le_prov_info->text().isEmpty())
        {
            QMessageBox::information(this, "注意", "未选定有效项目！");
            return false;
        }
    }

    if(ui->le_price_after->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "项目价格不可以为空白！");
        ui->le_price_after->setFocus();
        return false;
    }

    double testDouble = ui->le_price_after->text().trimmed().toDouble();
    if( qFuzzyCompare(testDouble, 0) || testDouble < 0)
    {
        QMessageBox::warning(this, "注意", "项目价格数值无效！");
        return false;
    }

    if( qFuzzyCompare(testDouble, ui->le_retail_price->text().toDouble()))
    {
        QMessageBox::warning(this, "注意", "项目价格无变化！");
        return false;
    }

    if( testDouble > ui->le_retail_price->text().toDouble())
    {
        profit_flag = "1";
    }
    else
    {
        profit_flag = "0";
    }
    return true;
}

void Form_com_jbgl::on_pb_gen_drug_price_list_clicked()
{
    dlgDelay->setText("正在导出数据。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    sq = "SELECT p.trade_name, c.center_item_grade, p.specs, p.retail_price, p.pack_unit, p.SELF_FLAG"
         " FROM pha_com_baseinfo p"
         " join drug_base_info b on b.DRUG_CODE = p.DRUG_CODE and b.valid = '1'"
         " left join FIN_COM_COMPARE c on c.fixmedins_hilist_id = p.DRUG_CODE"
         " order by p.SELF_FLAG, p.trade_name ";
    qro->exec(sq);

    qDebug()<<"提取价表："<<sq;

    QJsonDocument d;
    QJsonArray jsa_val;    //数值

    QJsonObject jot;  // 临时json
    int row = 2;

    int rowCount = 0;

    qro->exec(sq);
    while(qro->next())
    {
        row ++;
        rowCount ++ ;

        jot.insert("val", qro->value("trade_name").toString());
        jot.insert("row", row);
        jot.insert("col", 1);
        jsa_val << jot;

        QString grade = qro->value("center_item_grade").toString();
        if(grade == "01")
        {
            grade = "甲";
        }else if(grade == "02")
        {
            grade = "乙";
        }else if(grade == "03")
        {
            grade = "丙";
        }
        else
        {
            grade = "";
        }
        jot.insert("val", grade);
        jot.insert("row", row);
        jot.insert("col", 2);
        jsa_val << jot;

        jot.insert("val", qro->value("specs").toString());
        jot.insert("row", row);
        jot.insert("col", 3);
        jsa_val << jot;

        jot.insert("val", qro->value("pack_unit").toString());
        jot.insert("row", row);
        jot.insert("col", 4);
        jsa_val << jot;

        jot.insert("val", qro->value("retail_price").toString());
        jot.insert("row", row);
        jot.insert("col", 5);
        jsa_val << jot;

    }

    QJsonArray jsa_rng;    //表格区域
    jot = d.object();
    QString rg = QString("A4:E%1").arg(QString::number( rowCount + 3 ));
    jot.insert("range", rg);
    jsa_rng << jot;

    QJsonArray jsa_clr;    //清除区域
    jot = d.object();
    jot.insert("row1",3);
    jot.insert("row2",rowCount);
    jot.insert("col1",1);
    jot.insert("col2",5);
    jsa_clr << jot;


    QJsonObject jo; //打印参数
    jo.insert("excel_model", "/sheets/yaopinjiagebiao.xls");
    jo.insert("cell_value", jsa_val);
    jo.insert("grid_range", jsa_rng);
    jo.insert("process_mode", "s"); //只保存，不打印

    pub::printOutExcel(jo);

    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();

//    QFile fl(source_file);
//    if(!fl.exists())
//    {
//        QMessageBox::information(NULL, "注意", "生成报表文件失败！");
//        return;
//    }

//    if(fl.copy(fileName))
//    {
//        QString path = QDir::currentPath();
//        QMessageBox::information(NULL, "注意", "报表文件已生成，路径为 " + path.mid(0, 2) + fileName + "。");
//    }
//    else
//    {
//        QMessageBox::information(NULL, "注意", "复制报表文件失败！");
//    }

}

void Form_com_jbgl::on_pb_drug_price_save_clicked()
{

    if(md_drug_new_price->rowCount() < 1)
    {
        QMessageBox::information(this, "注意", "未录入有效调价项目！");
        return;
    }

    sq = "select SEQ_PHA_ADJUSTPRICE_ID.nextval from dual";
    qro->exec(sq);
    qro->next();
    adjust_number = qro->value(0).toString();

    qrm->exec("select * from tmp_price_detail order by serial_code");
    while(qrm->next())
    {
        sq = "insert into PHA_COM_ADJUSTPRICEINFO ("
             "adjust_number ,"   //调价单序号
                "serial_code ," //调价单内序号
                "drug_code , "//药品编码
                "trade_name  ,"  //trade_name
                "drug_dept_code  , " //库房编码
                "drug_type ,"    //药品类别
                "drug_quality ,"     //药品性质
                "specs ,"  //规格
                "producer ,"  //生产厂家
                "pack_unit ,"//包装单位
                "pack_qty , "//包装数量
                "min_unit ,"//最小单位
                "store_sum ,"        //调价库存量
                "pre_wholesale_price ,"  //调价前购入价格
                "pre_retail_price ,"     //调价前零售价格
                "wholesale_price ,"  //调价后购入价格
                "retail_price ,"     //调价后零售价格
                "current_state ,"//调价单状态：0、未调价；1、已调价；2、无效"
                "profit_flag , "//盈亏标记1-盈，0-亏
                "dd_adjust_mark , "//药库调价标志
                "ds_adjust_mark , "//药房调价标志
                "inure_time ,"  //调价执行时间
                "oper_code ,"    //
                "oper_name ,"   //
                "oper_date ,"  //
                "mark "    //
                ") values (";
        sq += adjust_number + ",";   //调价单序号
        sq += qrm->value("serial_code").toString() + ","; //调价单内序号
        sq += "'" + qrm->value("item_code").toString() + "',";//药品编码
        sq += "'" + qrm->value("item_name").toString() + "',";  //trade_name
        sq += "'0000',";//库房编码
        sq += "'" + qrm->value("drug_type").toString() + "',";  //药品类别
        sq += "'" + qrm->value("drug_quality").toString() + "',";    //药品性质
        sq += "'" + qrm->value("specs").toString() + "',";  //规格
        sq += "'" + qrm->value("producer_code").toString() + "',";  //生产厂家
        sq += "'" + qrm->value("pack_unit").toString() + "',";//包装单位
        sq += qrm->value("pack_qty").toString() + ",";//包装数量
        sq += "'" + qrm->value("min_unit").toString() + "',";//最小单位
        sq += qrm->value("store_sum").toString() + ",";//调价库存量
        sq += qrm->value("pre_wholesale_price").toString() + ","; //调价前购入价格
        sq += qrm->value("pre_retail_price").toString() + ",";  //调价前零售价格
        sq += qrm->value("wholesale_price").toString() + ",";//调价后购入价格
        sq += qrm->value("retail_price").toString() + ",";  //调价后零售价格
        sq += "'0',";//调价单状态：0、未调价；1、已调价；2、无效"
        sq += "'" + qrm->value("profit_flag").toString() + "',";//盈亏标记1-盈，0-亏
        sq += "'0',";//药库调价标志
        sq += "'0',";//药房调价标志
        sq += "sysdate, "; //调价执行时间
        sq += "'" + pub::usr_code + "',";  //
        sq += "'" + pub::usr_name + "',"; //
        sq += "sysdate,";  //
        sq += "'" + qrm->value("mark").toString() + "'";  //
        sq += ")";

        qDebug()<<"插入调价记录："<<sq;

        if(!qro->exec(sq))
        {
            QMessageBox::information(this, "注意", "保存调价数据失败！\n" + qro->lastError().text() );
            return;
        }
    }

    if(qro->exec("begin pkg_pha.prc_change_price; end;"))
    {
        QMessageBox::information(this, "注意", "调价数据保存完成！" );
        clear_screen();
        md_drug_new_price->setQuery(NULL);
        qrm->exec( "delete from tmp_price_detail ");
        serial_code = 0;
    }
}

void Form_com_jbgl::on_pb_remove_item_drug_clicked()
{
    if(!ui->tv_drug_dest->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未指定数据！" );
        return;
    }

    QString dgcd = ui->tv_drug_dest->currentIndex().siblingAtColumn(1).data().toString();
    sq = "delete from tmp_price_detail where item_code = '" + dgcd + "'";
    qrm->exec(sq);
    sq = "select item_name 项目名称, item_code 项目代码, pre_retail_price 调价前, retail_price 调价后 "
         " from tmp_price_detail order by serial_code";

    md_drug_new_price->setQuery(sq, pub::db_m);

    ui->tv_drug_dest->setModel(md_drug_new_price);
    int width = ui->tv_drug_dest->width();
    pub::setColumnWidth(ui->tv_drug_dest, "0.25^0.25^0.2^0.2^0^0^0^0^0", width);
}

void Form_com_jbgl::on_pb_add_item_drug_clicked()
{
    if(!check_status())
    {
        return;
    }

    serial_code++;//顺序号

    sq = "replace into tmp_price_detail "
         "(serial_code,"//顺序号
            "item_code , "//药品编码
            "item_name ,"  //trade_name
            "drug_type,"    //药品类别
            "drug_quality,"     //药品性质
            "specs ,"  //规格
            "producer_code,"  //生产厂家
            "pack_unit ,"//包装单位
            "pack_qty, "//包装数量
            "min_unit,"//最小单位
            "store_sum ,"        //调价库存量
            "pre_wholesale_price ,"  //调价前购入价格
            "pre_retail_price ,"     //调价前零售价格
            "wholesale_price ,"  //调价后购入价格
            "retail_price ,"     //调价后零售价格
            "profit_flag , "//盈亏标记1-盈，0-亏
            "mark "    //
            ") ";
    sq += " values(" + QString::number(serial_code) + ",";
    sq += "'" + item_info["drug_code"] + "',";
    sq += "'" + item_info["trade_name"] + "',";
    sq += "'" + item_info["drug_type"] + "',";
    sq += "'" + item_info["drug_quality"] + "',";
    sq += "'" + item_info["specs"] + "',";
    sq += "'" + item_info["producer_code"] + "',";
    sq += "'" + item_info["pack_unit"] + "',";
    sq += item_info["pack_qty"] + ",";
    sq += "'" + item_info["min_unit"] + "',";
    sq += item_info["store_sum"] + ",";
    sq += item_info["purchase_price"] + ",";
    sq += item_info["retail_price"] + ",";
    sq += item_info["purchase_price"] + ",";
    sq += ui->le_price_after->text() + ",";
    sq += "'" + profit_flag + "',";
    sq += "'" + ui->le_memo->text().trimmed() + "'";
    sq += ")";
    qDebug()<<"向临时表中增加调价项目："<<sq;
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "向临时表中增加调价项目失败！\n" + qro->lastError().text());
    }
    else
    {
        clear_screen();
        sq = "select item_name 项目名称, item_code 项目代码, pre_retail_price 调价前, retail_price 调价后 "
             " from tmp_price_detail order by serial_code";

        md_drug_new_price->setQuery(sq, pub::db_m);

        ui->tv_drug_dest->setModel(md_drug_new_price);
        int width = ui->tv_drug_dest->width();
        pub::setColumnWidth(ui->tv_drug_dest, "0.25^0.25^0.2^0.2^0^0^0^0^0", width);
    }

}
void Form_com_jbgl::clear_screen_u()
{
    ui->le_item_code_u->clear();
    ui->le_item_name_u->clear();
    ui->le_price_unit_u->clear();
    ui->le_retail_price_u->clear();
    ui->le_price_after_u->clear();

}
void Form_com_jbgl::clear_screen()
{
    ui->le_prov_info->clear();
    ui->le_factory->clear();
    ui->le_pack_qty->clear();
    ui->le_pack_unit->clear();
    ui->le_store_sum->clear();
    ui->le_purchase_price->clear();
    ui->le_retail_price->clear();
    ui->le_price_after->clear();
    ui->le_memo->clear();
}

void Form_com_jbgl::on_pb_exit_clicked()
{
    close();
}

void Form_com_jbgl::on_pb_search_undrug_clicked()
{

    QString key = ui->le_key_undrug->text().trimmed();
    sq = " select item_code 项目编码, item_name 项目名称, stock_unit, "
         " unit_price 现行价格 , unitflag "
         " from fin_com_undruginfo where 1 = 1  "
         " and( SPELL_CODE like '%%1%' or item_NAME like '%%2%' )";

    sq = sq.arg(key.toUpper()).arg(key);

    if(!ui->cbb_dept_code_2->currentText().isEmpty()
            && ui->cbb_dept_code_2->currentText() != "全部"
            )
    {
        int pos = pub::searchStr(oper_dept, "^", ui->cbb_dept_code_2->currentText());
        sq += " and exedept_code like '%" + pub::getStr(oper_dept, "^", pos + 1) + "%'";//
    }

    if(ui->ckb_inuse_undrug->isChecked())
    {
        //在用项目
        sq += " and valid_state = '1' ";
    }
    else
    {
        sq += " and valid_state = '0' ";
    }

    if(ui->ckb_combine->isChecked())
    {
        //组合项目
        sq += " and unitflag = '1' ";
    }
    else
    {
        sq += " and unitflag = '0' ";
    }

    sq += " order by item_name";

    qDebug()<<"非药品调价，目录检索："<<sq;
    md_undrug_list->setQuery(sq, pub::db_o);

    ui->tv_undrug_source->setModel(md_undrug_list);
    int width = ui->tv_undrug_source->width();
    pub::setColumnWidth(ui->tv_undrug_source, "0.25^0.5^0^0.2^0^0^0^0^0", width);

}

void Form_com_jbgl::on_tv_undrug_source_clicked(const QModelIndex &index)
{

    item_info.clear();
    item_info["item_name"] = index.siblingAtColumn(1).data().toString();
    item_info["item_code"] = index.siblingAtColumn(0).data().toString();
    item_info["cur_price"] = index.siblingAtColumn(3).data().toString();
    item_info["stock_unit"] = index.siblingAtColumn(2).data().toString();

    ui->le_item_code_u->setText(item_info["item_code"]);
    ui->le_item_name_u->setText(item_info["item_name"]);
    ui->le_price_unit_u->setText(item_info["stock_unit"]);
    ui->le_retail_price_u->setText(item_info["cur_price"]);
    ui->le_price_after_u->clear();

    ui->le_memo->clear();

    if(index.siblingAtColumn(4).data().toString() == "1")
    {
        //组合项目价格由明细项目生成，不可以直接修改
        ui->pb_add_item_undrug->setEnabled(false);
        ui->pb_remove_item_undrug->setEnabled(false);
    }
    else
    {
        ui->pb_add_item_undrug->setEnabled(true);
        ui->pb_remove_item_undrug->setEnabled(true);
    }

}

void Form_com_jbgl::on_pb_remove_item_undrug_clicked()
{
    if(!ui->tv_undrug_dest->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未指定数据！" );
        return;
    }

    QString dgcd = ui->tv_undrug_dest->currentIndex().siblingAtColumn(1).data().toString();
    sq = "delete from tmp_price_detail where item_code = '" + dgcd + "'";
    qrm->exec(sq);
    sq = "select item_name 项目名称, item_code 项目代码, pre_retail_price 调价前, retail_price 调价后 "
         " from tmp_price_detail order by serial_code";

    md_undrug_new_price->setQuery(sq, pub::db_m);

    ui->tv_undrug_dest->setModel(md_undrug_new_price);
    int width = ui->tv_undrug_dest->width();
    pub::setColumnWidth(ui->tv_undrug_dest, "0.25^0.25^0.2^0.2^0^0^0^0^0", width);
}

void Form_com_jbgl::on_pb_add_item_undrug_clicked()
{
    if(!check_status_u())
    {
        return;
    }

    serial_code++;//顺序号

    sq = "replace into tmp_price_detail "
         "(serial_code,"//顺序号
            "item_code , "//药品编码
            "item_name ,"  //trade_name
            "pack_unit ,"//包装单位
            "pre_retail_price ,"     //调价前零售价格
            "retail_price "     //调价后零售价格
            ") ";
    sq += " values(" + QString::number(serial_code) + ",";
    sq += "'" + item_info["item_code"] + "',";
    sq += "'" + item_info["item_name"] + "',";
    sq += "'" + item_info["stock_unit"] + "',";
    sq += item_info["cur_price"] + ",";
    sq += ui->le_price_after_u->text() ;
    sq += ")";
    qDebug()<<"向临时表中增加调价项目："<<sq;
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "向临时表中增加调价项目失败！\n" + qro->lastError().text());
    }
    else
    {
        clear_screen_u();
        sq = "select item_name 项目名称, item_code 项目代码, pre_retail_price 调价前, retail_price 调价后 "
             " from tmp_price_detail order by serial_code";

        md_undrug_new_price->setQuery(sq, pub::db_m);

        ui->tv_undrug_dest->setModel(md_undrug_new_price);
        int width = ui->tv_undrug_dest->width();
        pub::setColumnWidth(ui->tv_undrug_dest, "0.25^0.25^0.2^0.2^0^0^0^0^0", width);
    }
}

void Form_com_jbgl::on_pb_drug_price_save_u_clicked()
{
    if(md_undrug_new_price->rowCount() < 1)
    {
        QMessageBox::information(this, "注意", "未录入有效调价项目！");
        return;
    }

    sq = "select SEQ_COM_ADJUSTPRICE_NO.nextval from dual";
    qro->exec(sq);
    qro->next();
    adjust_number = qro->value(0).toString();

    qrm->exec("select * from tmp_price_detail order by serial_code");

    pub::db_o.transaction();

    //写入 FIN_COM_ADJUSTUNDRUGPRICEHEAD
    sq = "insert into FIN_COM_ADJUSTUNDRUGPRICEHEAD ("
         "adjustprice_no, begin_date, oper_code, oper_date)"
         "values(";
    sq += "'" + adjust_number + "',";
    sq += "to_date('0001-01-01', 'yyyy-mm-dd'),";
    sq += "'" + pub::usr_code + "',";
    sq += "sysdate )";

    qDebug()<<"写入 FIN_COM_ADJUSTUNDRUGPRICEHEAD : "<<sq;
    pub::db_o.exec(sq);
    if(pub::db_o.lastError().isValid())
    {
        QString str = "写入 FIN_COM_ADJUSTUNDRUGPRICEHEAD 发生错误 !\n " + pub::db_o.lastError().text();
        QMessageBox::information(this, "注意", str);
        pub::db_o.rollback();
        return;
    }

    while(qrm->next())
    {

        QString itmcd = qrm->value("item_code").toString();

        //写入 FIN_COM_ADJUSTUNDRUGPRICEDETAI
        sq = "insert into FIN_COM_ADJUSTUNDRUGPRICEDETAI (parent_code, current_code, "
             "adjustprice_no, item_code, unit_price_old,unit_price1_old,unit_price2_old,"
             " unit_price,unit_price1,unit_price2,oper_code,oper_date,valuestate)"
             " values("
             "'ROOT', 'ROOT',";
        sq += adjust_number + ","; //调价单序号
        sq += "'" + itmcd + "',";//药品编码
        sq += qrm->value("pre_retail_price").toString() + ",";  //调价前
        sq += qrm->value("pre_retail_price").toString() + ",";  //调价前
        sq += qrm->value("pre_retail_price").toString() + ",";  //调价前
        sq += qrm->value("retail_price").toString() + ",";  //调价后
        sq += qrm->value("retail_price").toString() + ",";  //调价后
        sq += qrm->value("retail_price").toString() + ",";  //调价后
        sq += "'" + pub::usr_code + "',";  //
        sq += "sysdate, '0' )";

        qDebug()<<"写入 FIN_COM_ADJUSTUNDRUGPRICEDETAI："<<sq;
        pub::db_o.exec(sq);
        if(pub::db_o.lastError().isValid())
        {
            QString str = "写入 FIN_COM_ADJUSTUNDRUGPRICEDETAI： 发生错误 !\n " + pub::db_o.lastError().text();
            QMessageBox::information(this, "注意", str);
            pub::db_o.rollback();
            return;
        }

        //更新 FIN_COM_UNDRUGINFO
        sq = "update FIN_COM_UNDRUGINFO set ";
        sq += "unit_price = " + qrm->value("retail_price").toString() + ",";
        sq += "unit_price1 = " + qrm->value("retail_price").toString() + ",";
        sq += "unit_price2 = " + qrm->value("retail_price").toString() + ",";
        sq += "oper_code = '" + pub::usr_code + "',";
        sq += "oper_date = sysdate";
        sq += " where item_code = '" + itmcd + "'";

        qDebug()<<"更新 FIN_COM_UNDRUGINFO："<<sq;
        pub::db_o.exec(sq);
        if(pub::db_o.lastError().isValid())
        {
            QString str = "更新 FIN_COM_UNDRUGINFO 发生错误 !\n " + pub::db_o.lastError().text();
            QMessageBox::information(this, "注意", str);
            pub::db_o.rollback();
            return;
        }

    }

    pub::db_o.commit();
    QMessageBox::information(this, "注意", "调价数据保存完成！" );

    qrm->first();
    while(true)
    {
        sq = " select PACKAGE_CODE from fin_com_undrugztinfo  " //
             " where HIS_CODE = '" + qrm->value("item_code").toString() + "'";

        qDebug()<<"提取包含此次调价明细项目的非药品组合："<<sq;

        if(!qro->exec(sq)){
            qDebug()<<qro->lastError().text();
            QMessageBox::information(this, "Note", "提取非药品组合失败！");
            break;
        }
        if(qro->next())
        {
            calculate_group_price(qro->value(0).toString());
        }

        if(!qrm->next())
        {
            break;
        }
    }

    clear_screen_u();
    md_undrug_new_price->setQuery(NULL);

    qrm->exec( "delete from tmp_price_detail ");

    serial_code = 0;

}

void Form_com_jbgl::on_pb_search_bill_clicked()
{
    if(ui->rb_drug->isChecked())
    {
        //药品
        sq = "select distinct adjust_number 调价单号 , inure_time 调价时间  "
             "from PHA_COM_ADJUSTPRICEBATCH  ";
        if(ui->ckb_one_year->isChecked())
        {
            sq += " where inure_time > sysdate - 365 ";
        }

        sq += "order by adjust_number desc ";

    }
    else
    {
        //非药品
        sq = "select distinct adjustprice_no 调价单号 , oper_date 调价时间  "
             "from FIN_COM_ADJUSTUNDRUGPRICEHEAD  ";
        if(ui->ckb_one_year->isChecked())
        {
            sq += " where oper_date > sysdate - 365 ";
        }

        sq += "order by adjustprice_no desc ";
    }

    qDebug()<<"筛选调价单列表："<<sq;

    md_bill_list->setQuery(sq, pub::db_o);

    ui->tv_bill_list->setModel(md_bill_list);
    int width = ui->tv_bill_list->width();
    pub::setColumnWidth(ui->tv_bill_list, "0.45^0.45^0^0^0^0^0^0^0", width);

}

void Form_com_jbgl::on_tv_bill_list_clicked(const QModelIndex &index)
{

    QString sn = index.siblingAtColumn(0).data().toString();

    if(ui->rb_drug->isChecked())
    {
        //药品
        sq = "select adj.drug_code 药品编码, adj.trade_name 药品名称, adj.pre_retail_price 调前价格, "
             " adj.retail_price 调后价格,"
             " adj.store_sum  / adj.pack_qty 调价数量, adj.pack_unit 单位"
             " from pha_com_adjustpriceinfo adj "
             " where adj.adjust_number = '" + sn + "'";
        sq += " order by serial_code ";
    }
    else
    {
        //非药品
        sq = "select un.item_code 项目编码, un.item_name 项目名称, adj.unit_price_old 调前价格, "
             "adj.unit_price 调后价格 from FIN_COM_ADJUSTUNDRUGPRICEDETAI adj "
             " left join fin_com_undruginfo un on un.item_code = adj.item_code "
             " where adj.adjustprice_no = '" + sn + "'";
    }

    qDebug()<<"调价单内容："<<sq;

    last_sql = sq;

    md_bill_content->setQuery(sq, pub::db_o);

    ui->tv_bill_content->setModel(md_bill_content);
    int width = ui->tv_bill_content->width();
    if(ui->rb_drug->isChecked())
    {
        pub::setColumnWidth(ui->tv_bill_content, "0.15^0.3^0.1^0.1^0.1^0.1^0^0^0", width);
    }else{
        pub::setColumnWidth(ui->tv_bill_content, "0.15^0.4^0.15^0.15^0^0^0^0^0", width);
    }


}

void Form_com_jbgl::on_le_key_undrug_returnPressed()
{
    on_pb_search_undrug_clicked();
}

void Form_com_jbgl::on_le_key_drug_returnPressed()
{
    on_pb_search_drug_clicked();
}

void Form_com_jbgl::on_pb_gen_drug_price_list_u_clicked()
{

}

void Form_com_jbgl::calculate_group_price(QString his_code)
{
    sq = " select sum(fin.unit_price) "
         " from fin_com_undruginfo "
         " where "
         " package_code = '" + his_code + "'";

    qDebug()<<"计算组套价格 ： "<<sq;

    if(!qro->exec(sq))
    {
        QMessageBox::information(this, "Note", "Calculate group price SQL error.");
        qDebug()<<qro->lastError().text();
        return;
    }

    qro->next();

    sq = "update fin_com_undruginfo set unit_price = %1 "
         " where item_code = '%2'";

    sq = sq.arg(qro->value(0).toDouble()).arg(his_code);

    qDebug()<<"修改组套价格 ： "<<sq;
    if(!qro->exec(sq))
    {
        QMessageBox::information(this, "Note", "Update group price SQL error.");
        qDebug()<<qro->lastError().text();
        return;
    }

}

void Form_com_jbgl::on_pb_export_clicked()
{
    if(last_sql.isEmpty())
    {
        QMessageBox::information(this,"注意","无有效查询记录！");
        return;
    }

    pub::export_sql_to_excel(last_sql, qro);

}
